package com.soundShape.mediators.specialDates
{
	
	import com.soundShape.events.SoundShapeEvent;
	import com.soundShape.mediators.AbstractViewMediator;
	import com.soundShape.popUps.AddSpecialDate;
	import com.soundShape.views.specialDates.SpecialDates;
	import com.soundShape.vo.CustomerVO;
	import com.soundShape.vo.SpecialDateVO;
	
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.events.ListEvent;
	import mx.managers.PopUpManager;
	
	import nz.co.codec.flexorm.criteria.Criteria;
	
	import spark.collections.SortField;
	import spark.components.DropDownList;
	import spark.events.IndexChangeEvent;
	
	
	
	
	public class SpecialDatesMediator extends AbstractViewMediator
	{
		
		
		
				
				public function SpecialDatesMediator()
				{
					super(SpecialDates);
				}
				
				/**
				 * Since the AbstractViewMediator sets the view via Autowiring in Swiz,
				 * we need to create a local getter to access the underlying, expected view
				 * class type.
				 */
				public function get view():SpecialDates
				{
					return this._view as SpecialDates;
				}
				
				/**
				 * The <code>init()</code> method is fired off automatically by the 
				 * AbstractViewMediator when the creation complete event fires for the
				 * corresponding ViewMediator's view. This allows us to listen for events
				 * and set data bindings on the view with the confidence that our view
				 * and all of it's child views have been created and live on the stage.
				 */
				override protected function init():void
				{
					super.init();
					
					this.setViews();
					
				}
				
				override protected function setViewDataBindings():void
				{
					super.setViewDataBindings();
				}	
				
				override protected function setViewListeners():void
				{
					super.setViewListeners();
					
					this.view.btnMenu.addEventListener(MouseEvent.CLICK, handleBtnMenu);
					
					this.view.dgSpecialDates.addEventListener(ListEvent.ITEM_CLICK, handleDgSpecialDatesEvent);
					
					this.view.ddCustomers.addEventListener(IndexChangeEvent.CHANGE,handleDDcustomersChange);
					
					this.view.dgSpecialDatesDetail.addEventListener(ListEvent.ITEM_CLICK,handleDetail);
				}
				
				protected function handleDetail(event:ListEvent):void
				{
					var specialDateVO:SpecialDateVO = ArrayCollection(this.view.dgSpecialDatesDetail.dataProvider).getItemAt(event.rowIndex) as SpecialDateVO;
					
					var addSpecialDate:AddSpecialDate = new AddSpecialDate();
					addSpecialDate.viewState = "Update";
					addSpecialDate.specialDateVO = specialDateVO;
					addSpecialDate.customerName = this.view.lblCurrentCustomer.text;
					addSpecialDate.employeeVO = this.applicationModel.employeeVO;
					addSpecialDate.entityManager = this.applicationModel.entityManager;
					addSpecialDate.callback = callbackAddSpecialDate;
					PopUpManager.addPopUp(addSpecialDate, this.view, true);
					PopUpManager.centerPopUp(addSpecialDate);
				}
				
				protected function handleDDcustomersChange(event:IndexChangeEvent):void
				{
					var customerVO:CustomerVO = DropDownList(event.target).selectedItem as CustomerVO;
					
					var addSpecialDate:AddSpecialDate = new AddSpecialDate();
					addSpecialDate.viewState = "Create";
					addSpecialDate.employeeVO = this.applicationModel.employeeVO;
					addSpecialDate.customerVO = customerVO;
					addSpecialDate.entityManager = this.applicationModel.entityManager;
					addSpecialDate.callback = callbackAddSpecialDate;
					PopUpManager.addPopUp(addSpecialDate, this.view, true);
					PopUpManager.centerPopUp(addSpecialDate);
				}
				
				private function callbackAddSpecialDate():void
				{
					//refresh the datagrids
					setViews();
				}
				
				protected function handleDgSpecialDatesEvent(listEvent:ListEvent):void
				{
					var obj:Object = ArrayCollection(this.view.dgSpecialDates.dataProvider).getItemAt(listEvent.rowIndex);
					
					var criteria:Criteria = applicationModel.entityManager.createCriteria(SpecialDateVO);
					criteria.addEqualsCondition("customerID",obj.customerID);
					var specialDateDetail:ArrayCollection = applicationModel.entityManager.fetchCriteria(criteria);
					
					var sort:Sort = new Sort();
					
					var sortField:SortField = new SortField();
					sortField.name = "specialDate";
					sortField.descending = false;
					
					sort.fields = [sortField];
					
					specialDateDetail.sort = sort;
					specialDateDetail.refresh();
					
					this.view.dgSpecialDatesDetail.dataProvider = specialDateDetail;
					
					this.view.lblCurrentCustomer.text = obj.name;
				}
				
				private function setViews():void
				{
					// get all Special Dates associated with customers
					var criteria0:Criteria = applicationModel.entityManager.createCriteria(CustomerVO);
					var criteria1:Criteria = applicationModel.entityManager.createCriteria(SpecialDateVO);
					
					var customers:ArrayCollection = applicationModel.entityManager.fetchCriteria(criteria0);
					
					var collSpecialDateSummary:ArrayCollection = new ArrayCollection();
					
					for each(var customerVO:CustomerVO in customers)
					{
						criteria1.addEqualsCondition("customerID",customerVO.id);
						var specialDates:ArrayCollection = applicationModel.entityManager.fetchCriteria(criteria1);
						var specialDateStr:String = "";
						
						if(specialDates.length != 0)
						{
							var collSpecialDates:ArrayCollection = new ArrayCollection();
							var arrSpecialDates:Array = [];
							
							for each(var specialDateVO:SpecialDateVO in specialDates)
							{
								collSpecialDates.addItem(specialDateVO.specialDate);
							}
							
							specialDateStr = doSortExtractSpecialDate(collSpecialDates);
						}
						
						var objSpecialDate:Object = {name:customerVO.name, value:specialDateStr, customerID:customerVO.id};
						
						collSpecialDateSummary.addItem(objSpecialDate);
					}
					
					doDisplayCustomerSpecialDates(collSpecialDateSummary);
					
					// do 'At a glance'
					findThisUpcoming(collSpecialDateSummary);
					findNextUpcoming(collSpecialDateSummary);
					
					//bind customers to 'create ...' panel
					this.view.ddCustomers.dataProvider = customers;
					
				}
				
				private function doSortExtractSpecialDate(coll:ArrayCollection):String
				{
					var sort:Sort = new Sort();
					
					var sortField:SortField = new SortField();
					sortField.descending = false;
					
					sort.fields = [sortField];
					
					coll.sort = sort;
					coll.refresh();
					
					var arr:Array = [];
					
					var n:int = 0;
					
					var spacer:String = "";
					
					for each(var obj:Object in coll)
					{
						if(n > 0)
							spacer = " ";
							
						arr.push(spacer + String(obj).split(" ")[1] + " " + String(obj).split(" ")[2]);
						n++;
					}
					
				return arr.toString();
				}		
				
				private function doDisplayCustomerSpecialDates(collSpecialDateSummary:ArrayCollection):void
				{
					var collSpecialDate:ArrayCollection = new ArrayCollection();
					
					for each(var obj:Object in collSpecialDateSummary)
					{
						if(obj.value != "")
						{
							collSpecialDate.addItem(obj);
						}
					}
					
					this.view.dgSpecialDates.dataProvider = collSpecialDate;
				}
				
				private var arrMonth:Array = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
				private var thisMonth:String;
				
				private function findThisUpcoming(coll:ArrayCollection):void
				{
					var thisDate:String = new Date().toString();
					thisMonth = thisDate.split(" ")[1];
					var arrCustomerSpecialDatesThisMonth:Array = [];
					var n:int = 0;
					var spacer:String = "";
					
					for each(var obj:Object in coll)
					{
						if(String(obj.value).indexOf(thisMonth) != -1)
						{
							(n > 0)
								spacer = " ";
								
							arrCustomerSpecialDatesThisMonth.push(spacer + obj.name);
							n++
						}
					}
					
					this.view.lblSpecialThisMonth.text = arrCustomerSpecialDatesThisMonth.toString();
				}
				
				private function findNextUpcoming(coll:ArrayCollection):void
				{
					var ndxThisMonth:int = arrMonth.indexOf(thisMonth);
					var arrCustomerSpecialDatesNextMonth:Array = [];
					var nextMonth:String;
					var n:int = 0;
					var spacer:String = "";
					
					if(ndxThisMonth < 12)
						nextMonth = arrMonth[ndxThisMonth+1];
					else
						nextMonth = "Jan";
					
					for each(var obj:Object in coll)
					{
						if(String(obj.value).indexOf(nextMonth) != -1)
						{
							(n > 0)
							spacer = " ";
							
							arrCustomerSpecialDatesNextMonth.push(spacer + obj.name);
							n++
						}
					}
					
					this.view.lblSpecialNextMonth.text = arrCustomerSpecialDatesNextMonth.toString();
				}
				
				/**
				 * *******************************************************************************
				 * Handlers
				 * *******************************************************************************
				 */
				private function handleBtnMenu(mouseEvent:MouseEvent):void
				{
					this.dispatcher.dispatchEvent(new SoundShapeEvent(SoundShapeEvent.SWITCH_TO_MENU_VIEW));
				}
				
				
				
				
				/**
				 * *******************************************************************************
				 * Swiz EventHanders
				 * *******************************************************************************
				 */
				
				/**
				 * *******************************************************************************
				 * util
				 * *******************************************************************************
				 */
				
				
			
		}
		
	}
